package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.pojo.Brand;
import com.leyou.item.dto.BrandDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.lang.management.BufferPoolMXBean;
import java.util.List;

@Service
public class BrandService {

    @Autowired
    private BrandMapper brandMapper;

    public PageResult<BrandDTO> pageQuery(Integer page, Integer rows,String sortBy,Boolean desc,String key) {

        //开启分页插件
        PageHelper.startPage(page,rows);

        //动态sql，的创建拼接工具
        Example example = new Example(Brand.class);

        //动态查询条件
        Example.Criteria criteria = example.createCriteria();

        if (StringUtils.isNotBlank(key)){//key不为空进行查询
            criteria.andLike("name","%"+key+"%");
        }


        //select * from tb_brand order by letter desc

        if (StringUtils.isNotBlank(sortBy)){

            example.setOrderByClause(sortBy+(desc?" DESC":" ASC"));//给example条件设置培训方案，此时相当于sql语句写好了order by
        }


        //使用通用mapper查询
        List<Brand> brands = this.brandMapper.selectByExample(example);

        //PageInfo
        //根据查询的情况统计符合当前查询的元素的总数，以及总页数信息
        PageInfo<Brand> pageInfo = new PageInfo<>(brands);

        //判断是否查到了内容
        if (CollectionUtils.isEmpty(brands)){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOND);
        }

        //把查询到的Brand集合转成BrandDto集合
        List<BrandDTO> brandDTOS = BeanHelper.copyWithCollection(brands, BrandDTO.class);

        //封装分页信息，总的元素个数，总的页码数，当前页内的数据集合
        return new PageResult<>(pageInfo.getTotal(),pageInfo.getPages(),brandDTOS);
    }

    @Transactional
    public void addBrand(BrandDTO brandDTO, List<Long> cids) {

        Brand brand = BeanHelper.copyProperties(brandDTO, Brand.class);

        //保存品牌信息，返回影响的行数,会自动主键回显
        int num = this.brandMapper.insertSelective(brand);

        if (num!=1){
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

        //下面要保存品牌和分类
        // 新增品牌和分类中间表,批量保存
        num = brandMapper.insertCategoryBrand(brand.getId(), cids);
        if(num != cids.size()){
            // 新增失败，抛出异常
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

    }

    @Transactional
    public void updateBrand(BrandDTO brandDTO, List<Long> cids) {

        Brand brand = BeanHelper.copyProperties(brandDTO, Brand.class);

       int count =  this.brandMapper.updateByPrimaryKeySelective(brand);

       if (1!=count){
           throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
       }
       //先删除所有的分类和当前品牌的关系，然后重新添加

        //TODO 各位在这里删除之前应该先统计品牌对应分类的个数，然后删除，一定要比对，数量相同才表示删除成功
        this.brandMapper.deleteCategoryBrand(brandDTO.getId());

       //重新添加

        // 重新插入中间表数据
        count = brandMapper.insertCategoryBrand(brand.getId(), cids);
        if(count != cids.size()){
            // 新增失败，抛出异常
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

    }

    public BrandDTO queryBrandById(Long brandId) {
        Brand brand = this.brandMapper.selectByPrimaryKey(brandId);

        return BeanHelper.copyProperties(brand,BrandDTO.class);
    }

    public List<BrandDTO> queryByCategoryId(Long id) {

       List<Brand> brands =  this.brandMapper.queryByCategoryId(id);

       if (CollectionUtils.isEmpty(brands)){
           throw new LyException(ExceptionEnum.BRAND_NOT_FOND);
       }
        return BeanHelper.copyWithCollection(brands,BrandDTO.class);
    }

    public List<BrandDTO> queryBrandByIds(List<Long> ids) {

        List<Brand> brands = this.brandMapper.selectByIdList(ids);

        if (CollectionUtils.isEmpty(brands)){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOND);
        }

        return BeanHelper.copyWithCollection(brands,BrandDTO.class);
    }
}
